package com.hdc.mumuwei.micro_account_server.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdc.mumuwei.micro_account_server.common.dto.AuthDto;
import com.hdc.mumuwei.micro_account_server.po.Paging;
import com.hdc.mumuwei.micro_account_server.po.User;
import com.hdc.mumuwei.micro_account_server.service.UserService;
import com.hdc.mumuwei.micro_account_server.utils.PassUtils;
import com.hdc.mumuwei.micro_account_server.utils.Result;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @author Mumuwei
 * @Description
 * @create 2021/11/19 22:48
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.appSecret}")
    private String appSecret;

    @PostMapping("register")
    public Result registerUser(User user) {
        return userService.registerUser(user);
    }

    @PostMapping("login")
    public Result login(User user) {
        return userService.login(user);
    }

    @GetMapping("loginWeixin/{code}")
    public Result loginWeixin(@PathVariable String code){
        String openId = requestOpenId(code);
        return userService.loginWeixin(openId);
    }

    @PostMapping("editPassword")
    public Result editPass(User user) {
        return userService.editPass(user);
    }

    @GetMapping("resetPass")
    public Result resetPassByEmail(String email) {
        return userService.resetPassByEmail(email);
    }

    @PostMapping("editUser")
    public Result editUserInfo(User user) {
        return userService.editUserInfo(user);
    }

    @GetMapping("emailConfirm")
    public Result confirmEmail(String email) {
        return userService.confirmEmail(email);
    }

    @GetMapping("getUserById")
    public Result getUserById(Integer uid){
        return userService.getUserById(uid);
    }

    @PostMapping("admin/addUser")
    public Result addUser(User user) {
        return userService.addUser(user);
    }

    @PostMapping("admin/editUser")
    public Result editUserInfoByAdmin(User user) {
        return userService.editUserInfoByAdmin(user);
    }

    @DeleteMapping("admin/deleteUser")
    public Result delUser(Integer id) {
        return userService.delUser(id);
    }

    @PostMapping("admin/editUserPass")
    public Result resetPassByAdmin(User user) {
        return userService.resetPassByAdmin(user);
    }

    @GetMapping("admin/getAllUser")
    public Result getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("admin/getUserList")
    public Result getUserList(Paging paging) {
        return userService.getUserList(paging);
    }

    private String requestOpenId(String code){
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        HttpGet get = new HttpGet(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            get.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(get);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            // System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
                // System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                // System.out.println("响应内容为:" + result);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        AuthDto authDto = JSONObject.parseObject(result, AuthDto.class);
        return authDto.getOpenid();
    }
}
